package com.smssalama.gui;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.TextField;

import com.smssalama.AlertManager;
import com.smssalama.SMSSalama;
import com.smssalama.SMSSalamaSession;
import com.smssalama.i18n.CommandLabels;
import com.smssalama.i18n.Labels;
import com.smssalama.i18n.ScreenTitles;
import com.smssalama.storage.contact.Contact;

/**
 * A form prompting for password for authentication
 * 
 * @author Arnold P. Minde
 */
public class Login extends Form implements CommandListener {
	CommandLabels LABELS = CommandLabels.cmdLabels();
	
	TextField password = new TextField(Labels.labels().password(), "", 15,
			TextField.ANY);

	private Displayable next;
	
	public Login(Displayable next) {
		super(ScreenTitles.screenTitles().signIn());
		this.next = next;
		setCommandListener(this);

		addCommand(new Command(LABELS.exit(), Command.EXIT, 1));
		addCommand(new Command(LABELS.ok(), Command.OK, 1));

		this.password.setLayout(Item.LAYOUT_CENTER | Item.LAYOUT_VCENTER);
		this.password.setConstraints(TextField.ANY | TextField.PASSWORD);
		this.password.setMaxSize(30);
		this.password.setPreferredSize(Integer.MAX_VALUE, -1);
		this.append(this.password);
	}
	public Login() {
		this(null);
	}
	public void commandAction(Command command, Displayable displayable) {
		if (command.getCommandType() == Command.EXIT) {
			SMSSalama.quitApp();
		} else if (command.getCommandType() == Command.OK) {
			try {
				performLogin();
			} catch (Exception ex) {
				AlertManager.showError(this, ex);
			}
		}
	}

	private void performLogin() throws Exception {
		if (SMSSalamaSession.getSession().authenticate(
				this.password.getString())) {
			if(this.next==null){
				AlertManager.showDisplayable(Home.getHomeScreen());
			}else{
				AlertManager.showDisplayable(this.next);
			}
			Runnable r = new Runnable() {
				public void run() {
					for (int i = 0; i < 100; i++) {
						Contact c = new Contact();
						c.setContactName("Contact Name " + i);
						c.setPhoneNumber("+" + i);
						c.setSharedKey("123");
						try {
							SMSSalamaSession.getSession().getUserSettings()
									.getContactsStore().persistStorable(c);
						} catch (Exception e) {
							e.printStackTrace();
							throw new RuntimeException(e.getMessage());
						}
					}
				}
			};
			//new Thread(r).start();
		} else {
			AlertManager.showError("Authentication failed");
			this.password.setString("");
		}
	}
}
